
//
//  MeituanRefreshView.swift
//  自定义刷新控件
//
//  Created by YYY on 2017/11/1.
//  Copyright © 2017年 成品家（北京）网络科技有限公司. All rights reserved.
//

import UIKit

private let kMaxHeight: CGFloat = 165
class MeituanRefreshView: UIView {

    init() {
        super.init(frame: CGRect())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //房子
    private lazy var houseImageView = UIImageView(image: UIImage(named: "房子1"))
    
    //地球
    private lazy var earthImageView = UIImageView(image: UIImage(named: "地球"))
    
    //袋鼠
    private lazy var kangarooImageView = UIImageView(image: UIImage(named: "袋鼠"))
    //刷新状态
    var refershState: PullUpState = .Normal
    
    //父视图高度
    var parmentHeight: CGFloat = 0
    {
        didSet
        {
            //40 - 165
            if parmentHeight < 21 {
                return
            }
            var scale: CGFloat = 0
            if parmentHeight > kMaxHeight
            {
                scale = 1
            }
            else
            {
                scale = 1 - (kMaxHeight - parmentHeight)/(kMaxHeight - 21)
            }
            kangarooImageView.transform = CGAffineTransform(scaleX: scale, y: scale)
        }
    }
    
}

extension MeituanRefreshView
{
    func setupUI()
    {
        clipsToBounds = true

        addSubview(houseImageView)
        addSubview(earthImageView)
        addSubview(kangarooImageView)
        
        frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 120)
        //设置房子的图片数组
        houseImageView.center.x = center.x
        let houseImage1 = #imageLiteral(resourceName: "房子1")
        let houseImage2 = #imageLiteral(resourceName: "房子2")
        houseImageView.image = UIImage.animatedImage(with: [houseImage1, houseImage2], duration: 0.5)

        //设置地球的旋转动画
        earthImageView.setTop(newTop: houseImageView.bottom - 35)
        earthImageView.center.x = center.x
        
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.toValue = -2 * Double.pi
        animation.repeatCount = MAXFLOAT
        animation.duration = 3
        //完成后不移除
        animation.isRemovedOnCompletion = false
        earthImageView.layer.add(animation, forKey: nil)
        
        //袋鼠
        let kangarooImage1 = #imageLiteral(resourceName: "袋鼠")
        let kangarooImage2 = #imageLiteral(resourceName: "袋鼠1")
        kangarooImageView.image = UIImage.animatedImage(with: [kangarooImage1, kangarooImage2], duration: 0.3)
        
        //设置锚点
        kangarooImageView.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
        //kangarooImageView.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
        kangarooImageView.center = CGPoint(x: center.x, y: bounds.height - 21)
    }
}
